import React from 'react';
import {
  Row,
  Col,
  Table,
  Icon,
  Switch,
  notification,
  Modal,
  Form,
  Input,
  Tooltip,
  Button,
  Checkbox,
  AutoComplete
} from 'antd';
import axios from 'axios';
import intercept from '../../utils/intercept';
import { config } from 'utils';
import moment from 'moment';
import './less/common.less';
const FormItem = Form.Item;
const CheckboxGroup = Checkbox.Group;
const Option = AutoComplete.Option;
class UserLists extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      dataSource: [],
      loading: false,
      pagination: {
        current: 1,
        pageSize: 10
      },
      onChange: this.onChange,
      keyword: '',
      visible: false,
      isChecked: false,
      userOrgans: ['省联网', '郑州市'],
      edituserinfo: ''
    };
  };

  componentDidMount() {
    this.getUserInfo();
    this.getUserOrgans();
  };

  search(value) {
    this.setState({ keyword: value });
    this.getUserInfo({ keyword: value });
  }

  onChange = (pagination, filters, sorter) => {
    this.getUserInfo({
      sortField: sorter.field,
      sortOrder: sorter.order,
      page: pagination.current,
      keyword: this.state.keyword,
      ...filters
    });
  };
  getUserOrgans = () => {
    const token = sessionStorage.getItem("token");
    axios
      .get(`${config.api}User/GetOrgansKey`, {
        headers: {
          Authorization: 'Bearer ' + token
        }
      })
      .then((res) => {
        let tmp = res
          .data
          .userOrgans
          .map(m => (
            <Option key={m.key} value={m.label}>
              {m.label}
            </Option>
          ));
        this.setState({ userOrgans: tmp });
      })
      .catch(err => {
        intercept
      })
  }
  getUserInfo = (params = {}) => {
    const token = sessionStorage.getItem("token");
    this.setState({ loading: true });
    var keyword = typeof (params.keyword) === "undefined"
      ? ''
      : params.keyword;
    axios
      .get(`${config.api}User/GetUserList?page=${params.page}&pageSize=${this.state.pagination.pageSize}&keyword=${keyword}`, {
        headers: {
          Authorization: 'Bearer ' + token
        }
      })
      .then((data) => {
        const pagination = {
          ...this.state.pagination
        };
        pagination.total = data.data.pageList.totalRows;
        pagination.current = params.page;
        this.setState({ loading: false, dataSource: data.data.pageList.collections, pagination });
      })
      .catch(err => {
        intercept
      })
  };
  switchChange = (checked, userName) => {
    const token = sessionStorage.getItem("token");
    axios.post(`${config.api}User/EnableUser`, {
      userName: userName,
      isEnable: checked
    }, {
        headers: {
          Authorization: 'Bearer ' + token
        }
      }).then((res) => {
        if (res.data.result) {
          this.openNotification("启用禁用用户", `${checked
            ? '启用'
            : '禁用'}用户成功`, "#108ee9");
        } else {
          this.openNotification("启用禁用用户", res.data.errorMessage, "red");
        }
      })
      .catch(err => {
        intercept
      })
  }
  unlocked = (checked, userName) => {
    const token = sessionStorage.getItem("token");
    axios.post(`${config.api}User/LockedUser`, {
      userName: userName,
      locked: checked
    }, {
        headers: {
          Authorization: 'Bearer ' + token
        }
      }).then((res) => {
        if (res.data.result) {
          this.openNotification("启用禁用用户", `${checked
            ? '锁定'
            : '解锁'}用户成功`, "#108ee9");
        } else {
          this.openNotification("锁定解锁用户", res.data.errorMessage, "red");
        }
      })
      .catch(err => {
        intercept
      })
  }
  openNotification = (title, desc, color) => {
    notification.open({
      message: title, description: desc, icon: <Icon type="smile-circle" style={{
        color: color
      }} />
    });
  };
  handleReset = () => {
    this
      .props
      .form
      .resetFields();
  }
  handleCancel = (e) => {
    this.setState({ visible: false });
  }
  editUser = (ev, record) => {
    //console.log(record);
    this
      .props
      .form
      .setFieldsValue({
        userName: record.userName,
        realName: record.realName,
        tel: record.phoneNumber,
        email: record.email,
        password: record.passwordHash,
        roles: record.userRoles,
        organcode: record.userOrgan,
        isEnable: record.isEnable
      });
    this.userid = record.id;
    this.setState({ visible: true, isChecked: record.isEnable, edituserinfo: record });
  }
  selectRoleChange = () => { }
  editUserInfo = (e) => {
    e.preventDefault();
    this
      .props
      .form
      .validateFieldsAndScroll((err, values) => {
        if (!err) {
          const token = sessionStorage.getItem("token");
          let postdata = {
            userid: this.userid,
            userName: values.userName,
            realName: values.realName,
            organName: values.organcode,
            phone: values.tel,
            email: values.email,
            roles: values.roles,
            isEnable: values.isEnable,
            password: values.password
          }
          axios
            .post(`${config.api}User/EidtUserInfo`, postdata, {
              headers: {
                Authorization: 'Bearer ' + token
              }
            })
            .then((data) => {
              //console.log("接口返回：",data);
              if (data.data.result) {
                this.openNotification("编辑用户", "编辑用户成功", "#108ee9");
                this
                  .props
                  .form
                  .resetFields();
              } else {
                this.openNotification("编辑用户", data.data.errorMessage, "red");
              }
              let datasource = this.state.dataSource;
              for (let i = 0; i < datasource.length; i++) {
                if (datasource[i].id === postdata.userid) {
                  let tmp = { ...datasource[i], ...postdata };
                  datasource[i] = tmp;
                }
              }
              this.setState({ visible: false, isChecked: false, dataSource: datasource });
            })
            .catch(err => {
              intercept
            })
        }
      });
  }

  showAddUserModel = () => {
    this.userid = '';
    this
      .props
      .form
      .resetFields();
    this.setState({ visible: true });
  }
  deletetUser = (ev, record) => {
    //console.log(record);
    const token = sessionStorage.getItem("token");
    let postdata = {
      userid: record.id
    }
    axios
      .post(`${config.api}User/DeleteUser`, postdata, {
        headers: {
          Authorization: 'Bearer ' + token
        }
      })
      .then((data) => {
        //console.log("接口返回：",data);
        if (data.data.result) {
          this.openNotification("删除用户", "删除用户成功", "#108ee9");
          this
            .props
            .form
            .resetFields();
          let dataSource = this.state.dataSource.filter(item => item.id !== record.id);;
          this.setState({
            dataSource
          })
        } else {
          this.openNotification("删除用户", data.data.errorMessage, "red");
        }
      })
      .catch(err => {
        intercept
      })
  }
  render() {
    const Search = Input.Search;
    const columns = [
      {
        title: '用户名',
        dataIndex: 'userName',
        width: 150
      }, {
        title: '姓名',
        dataIndex: 'realName',
        width: 150
      }, {
        title: '单位',
        dataIndex: 'userOrgan',
        width: 150
      }, {
        title: '手机号',
        dataIndex: 'phoneNumber',
        width: 150
      }, {
        title: '创建时间',
        dataIndex: 'createTime',
        width: 150,
        render: (text, record) => {
          return (
            <span>{new moment(record.createTime).format('YYYY-MM-DD HH:mm')}</span>
          )
        }
      }, {
        title: '最后登录时间',
        dataIndex: 'lastLoginTime',
        width: 150,
        render: (text, record) => {
          return (
            <span>{new moment(record.lastLoginTime).format('YYYY-MM-DD HH:mm')}</span>
          )
        }
      }, {
        title: '启用',
        dataIndex: 'isEnable',
        width: 150,
        render: (text, record) => {
          return (<Switch
            checkedChildren="开"
            unCheckedChildren="关"
            onChange={(checked, productCode) => {
              this.switchChange(checked, record.userName)
            }}
            defaultChecked={record.isEnable} />)
        }
      }, {
        title: <span>锁定<Tooltip title="锁定后用户无法登录">
          <Icon type="question-circle-o" />
        </Tooltip>
        </span>,
        dataIndex: 'lockoutEnabled',
        width: 150,
        render: (text, record) => {
          return (<Switch
            checkedChildren="锁定"
            unCheckedChildren="解锁"
            onChange={(checked, userName) => {
              this.unlocked(checked, record.id)
            }}
            defaultChecked={record.lockoutEnabled} />)
        }
      }, {
        title: '操作',
        width: 150,
        key: 'action',
        render: (text, record) => {
          return (
            <span>
              <a onClick={(ev, record) => this.editUser(ev, text)}>编辑</a>
              <span className="ant-divider" />
              <a onClick={(ev, record) => this.deletetUser(ev, text)}>删除</a>
            </span>
          )
        }
      }
    ];
    const { getFieldDecorator } = this.props.form;
    const className = "components-table-demo-nested";
    const scroll = {
      y: 600
    };
    const formItemLayout = {
      labelCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 6
        }
      },
      wrapperCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 14
        }
      }
    };
    const plainOptions = [
      '省级管理员',
      '省级运维角色',
      '省级客服角色',
      '省级开发人员角色',
      '营销管理',
      '省级财务角色',
      '定制客运管理员',
      '城际约租管理员',
      '汽车站管理员',
      '汽车站运维角色',
      '汽车站财务角色',
      '旅游站管理员',
      '报表统计角色'
    ];
    return (
      <div className="orderinfo">
        <Row gutter={8} style={{
          marginTop: '20px'
        }}>
          <Col span={24}>
            <div
              style={{
                textAlign: 'center',
                margin: 10
              }}>
              <Search
                placeholder="请输入任意查询条件"
                style={{
                  width: 600
                }}
                onSearch={value => this.search(value)} />
              <Button type="primary" className='newadd' onClick={this.showAddUserModel}>添加用户</Button>
            </div>
            <Table
              {...this.state}
              bordered={true}
              rowKey=
              {record => record.id}
              className={className}
              columns={columns}
              scroll={scroll} />
          </Col>
        </Row>
        <Modal
          title="编辑用户信息"
          width={1000}
          visible={this.state.visible}
          footer={null}
          onCancel={this.handleCancel}>
          <Form onSubmit={this.editUserInfo}>
            <FormItem
              {...formItemLayout}
              label={(
                <span>
                  用户名
                <Tooltip title="自动填充">
                    <Icon type="question-circle-o" />
                  </Tooltip>
                </span>
              )}
              hasFeedback>
              {getFieldDecorator('userName', {
                rules: [
                  {
                    required: true,
                    message: 'Please input your startandend!',
                    whitespace: true
                  }
                ]
              })(<Input />)}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label={(
                <span>
                  姓名
                <Tooltip title="自动填充">
                    <Icon type="question-circle-o" />
                  </Tooltip>
                </span>
              )}
              hasFeedback>
              {getFieldDecorator('realName', {
                rules: [
                  {
                    required: true,
                    message: 'Please input your startandend!',
                    whitespace: true
                  }
                ]
              })(<Input />)}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label={(
                <span>
                  手机号
                <Tooltip title="自动填充">
                    <Icon type="question-circle-o" />
                  </Tooltip>
                </span>
              )}
              hasFeedback>
              {getFieldDecorator('tel', {
                rules: [
                  {
                    required: true,
                    message: 'Please input your startandend!',
                    whitespace: true
                  }
                ]
              })(<Input />)}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label={(
                <span>
                  邮箱
                <Tooltip title="自动填充">
                    <Icon type="question-circle-o" />
                  </Tooltip>
                </span>
              )}
              hasFeedback>
              {getFieldDecorator('email', {
                rules: [
                  {
                    required: true,
                    message: 'Please input your startandend!',
                    whitespace: true
                  }
                ]
              })(<Input />)}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label={(
                <span>
                  密码
                <Tooltip title="自动填充">
                    <Icon type="question-circle-o" />
                  </Tooltip>
                </span>
              )}
              hasFeedback>
              {getFieldDecorator('password', {
                rules: [
                  {
                    required: true,
                    message: 'Please input your startandend!',
                    whitespace: true
                  }
                ]
              })(<Input />)}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label={(
                <span>
                  角色
                <Tooltip title="自动填充">
                    <Icon type="question-circle-o" />
                  </Tooltip>
                </span>
              )}
              hasFeedback>
              {getFieldDecorator('roles', {})(<CheckboxGroup options={plainOptions} onChange={this.selectRoleChange} />)}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label={(
                <span>
                  单位
                <Tooltip title="自动填充">
                    <Icon type="question-circle-o" />
                  </Tooltip>
                </span>
              )}
              hasFeedback>
              {getFieldDecorator('organcode', {
                rules: [
                  {
                    required: true,
                    message: 'Please input your startandend!',
                    whitespace: true
                  }
                ]
              })(<AutoComplete
                dataSource={this.state.userOrgans}
                filterOption={(inputValue, option) => option.props.children.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1} />)}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label={(
                <span>
                  是否启用
                <Tooltip title="自动填充">
                    <Icon type="question-circle-o" />
                  </Tooltip>
                </span>
              )}
              hasFeedback>
              {getFieldDecorator('isEnable', {
                rules: [
                  {
                    required: true,
                    type: 'boolean',
                    message: 'Please input your traderaccount!',
                    whitespace: true
                  }
                ]
              })(<Switch defaultChecked={this.state.isChecked} />)}
            </FormItem>
            <Row>
              <Col span={24}>
                <FormItem className="center">
                  <Button onClick={this.handleReset}>重置</Button>{' '}
                  <Button type="primary" htmlType="submit">确定</Button>
                </FormItem>
              </Col>
            </Row>
          </Form>
        </Modal>
      </div>
    )
  }
}
const UserList = Form.create()(UserLists);
export default UserList
